<!--
 * @Descripttion: 组装汇总
 * @Author: xiaojia
 * @Date: 2020-11-27 16:36:27
-->
<template>
  <a-card :bordered="false" title>
    <div v-show="showSpin">
      <a-spin tip="正在导出..." size="large">
        <div class="spin-content"></div>
      </a-spin>
    </div>
    <!-- 顶部查询 -->
    <a-form-model :model="formdata" v-bind="layout">
      <a-row>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="成套件仓库名称">
            <a-select v-model="formdata.pkStordoc" mode="multiple">
              <a-select-option
                v-for="item in WarehouseCodeList"
                :key="item.value"
                :value="item.pkStordoc"
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="成套件名称">
            <a-select
              v-model="formdata.packageInventory"
              showSearch
              @change="invcodeAftereChange"
              :default-value="['a1', 'b2']"
            >
              <a-select-option
                v-for="item in stockClassificationList"
                :key="item.partsInventoryId"
                :value="
                  item.partsInventoryNo +
                  '|' +
                  item.partsInventoryName +
                  '|' +
                  item.key +
                  '|' +
                  item.packageInventoryId
                "
                >{{ item.partsInventoryNo }}
                {{ item.partsInventoryName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :md="8" :sm="24">
          <a-form-model-item label="农户">
            <a-select
              v-model="formdata.clientId_dictText"
              @change="getfarmerId"
              @search="getAllfarmerList"
              showSearch
            >
              <a-select-option
                v-for="item in supplierList"
                :key="item.id"
                :value="item.No + '|' + item.name + '|' + item.id"
              >
                {{ item.No }} {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="会计日期">
            <a-range-picker
              format="YYYY-MM"
              @change="onChange"
              v-model="formdata.AccountingDate"
            /> </a-form-model-item
        ></a-col>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="业务日期">
            <a-range-picker
              format="YYYY-MM-DD"
              @change="onChange"
              v-model="formdata.dateOfSignature"
            />
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :style="{ textAlign: 'right' }">
          <a-button
            type="primary"
            style="margin-right: 8px"
            @click="onSubmit()"
          >
            查询
          </a-button>
          <a-button style="margin-right: 8px" @click="reset()"> 重置 </a-button>
          <a-button style="margin-right: 8px" @click="exportToExcel()">
            导出
          </a-button>
        </a-col>
      </a-row>

      <br />
    </a-form-model>
    <!-- 列表显示 --->
    <a-form-model>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 1100, y: 1000 }"
        id="myTable"
      >
        <span slot="action" slot-scope="text, record">
          <a @click="workupdate(record)" type="primary"> 编辑 </a>
          <a-divider type="vertical" />
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="workdelete(record)"
          >
            <template slot="title">
              <p>确定删除？</p>
            </template>
            <a type="danger"> 删除 </a>
          </a-popconfirm>
        </span>
      </a-table>
    </a-form-model>
  </a-card>
</template>
<script>
import moment from "moment";
import FileSaver from "file-saver";
import { sheet2blob } from "@/utils/export.js";
import XLSX from "xlsx";
import { ZuZhuangHuiZongHttp } from "../../services/modules/ChaXunYuTongJi/ZuZhuangHuiZong.js";
const $http = new ZuZhuangHuiZongHttp();
// import { ZiDianBiaoHttp } from "@/services/modules/ZiDianBiao.js";
// const zdbHttp = new ZiDianBiaoHttp(); // 字典表
import { CommonAjax } from "../../services/modules/common.js";
const comhttp = new CommonAjax();
export default {
  data() {
    return {
      showSpin: false, //打印加载中
      size: "default", //多选框的大小
      WarehouseCodeList: [], //所属单位（多选）字典表
      depotNameList: [],
      stockClassificationList: [],
      supplierList: [], //农户
      no: 0,
      updatevisible: false, //编辑弹窗
      dataSource: [],
      //列表分页
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      },
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
      },
      queryStr: "",
      //顶部查询条件
      formdata: {
        pkStordoc: [], //仓库名称
        packageInventory: [], //成套件名称
        // stockCode: "", //存货编码
        // stockCode1: "",
        // stockCode2: "",
        // stockName: "",
        farmer: "", //农户
        dateOfSignature: [], //业务日期
        AccountingDate: [], //会计日期
      },
      layout: {
        labelCol: { span: 8 }, //字
        wrapperCol: { span: 15 }, //框内大小
      },
      columns: [
        {
          title: "序号 ",
          // customRender: (text, record, index) => `${index + 1}`,
          dataIndex: "key",
          key: "key",
          align: "center",
        },
        {
          title: "成套件仓库名称",
          dataIndex: "depotName",
          align: "center",
        },

        {
          title: "成套件名称",
          dataIndex: "inventoryName",
          align: "center",
        },

        {
          title: "成套件规格型号",
          dataIndex: "specificationsModel",
          align: "center",
        },

        {
          title: "成套件单位",
          dataIndex: "unit",
          align: "center",
        },
        {
          title: "成套件数量",
          dataIndex: "sumQuantity",
          align: "center",
        },
        {
          title: "配件仓库名称",
          dataIndex: "stornameAfter",
          align: "center",
        },
        {
          title: "配件名称",
          dataIndex: "partsInventoryName",
          align: "center",
        },
        {
          title: "配件规格型号",
          dataIndex: "partsSpecificationsModel",
          align: "center",
        },
        {
          title: "配件单位",
          dataIndex: "partsUnit",
          align: "center",
        },
        {
          title: "配件数量",
          dataIndex: "partsSumQuantity",
          align: "center",
        },
      ],
    };
  },
  methods: {
    getApplyStorage() {
      this.WarehouseCodeList = [];
      // 获取仓库名称
      comhttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            id: res.result[i].pkStordoc,
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            pkStordoc: res.result[i].pkStordoc,
          };
          this.WarehouseCodeList.push(data);
        }
        console.log("返回仓库编码、仓库名称", this.WarehouseCodeList);
      });
    },
    // 获取成套件信息列表
    getPartsInventoryInformationList() {
      this.stockClassificationList = [];
      comhttp.getAllPackageList().then((res) => {
        console.log("所有的成套件", res);
        for (let i = 0; i < res.result.list.length; i++) {
          let data = {
            key: i + 1,
            // 配件
            packageInventoryId:
              res.result.list[i].packageInventoryInformationId, // 配件Id
            partsInventoryNo: res.result.list[i].packageInventoryNo, // 配件No
            partsInventoryName:
              res.result.list[i].packageInventoryInformationId_dictText, // 配件名稱
            packageInventoryStandardModel:
              res.result.list[i].specificationsModel, // 配件规格型号
            packageInventoryUnit: res.result.list[i].unit, // 配件单位
          };
          this.stockClassificationList.push(data);
        }
      });
    },
    // 获取供应商列表
    getfarmerId(value, options) {
      console.log("供应商::::", value, options.key);
      let array = value.split("|");
      console.log("array", array);
      // this.form.supplier_dictText = array[1];
      // this.form.supplier = array[2];
      this.$set(this.formdata, "clientId_dictText", array[1]);
      this.$set(this.formdata, "clientId", array[2]);
    },
    getAllfarmerList(value) {
      if (value != "") {
        comhttp
          .queryByLikeName("?customerName=" + value + "&custflag=1,3")
          .then((res) => {
            this.supplierList = [];
            console.log("所有的供应商信息::::", res);
            for (let i = 0; i < res.result.list.length; i++) {
              let data = {
                No: res.result.list[i].custcode, //编号
                id: res.result.list[i].pkCumandoc,
                name: res.result.list[i].custname,
              };

              this.supplierList.push(data);
            }
          });
        console.log("this.supplierList", this.supplierList);
      }
    },
    //获取列表
    getlist() {
      const { current } = this.pagination;
      let query = `?pageNo=${current}&auditMark=1${this.queryStr}`;
      $http.zuzhuangselect(query).then((res) => {
        console.log("组装汇总列表", res);
        this.pagination.current = res.result.pageNo;
        this.pagination.total = res.result.total;
        this.pagination.pageSize = res.result.pageSize;
        this.maxSize = res.result.total; //导出用
        let dataSource = [];
        const data = res.result.list;
        for (let i = 0; i < data.length; i++) {
          let Data = {
            key: i + (current - 1) * res.result.pageSize + 1,
            depotName: data[i].stornameBefore, //成套件仓库名称
            inventoryName: data[i].invnameBefore, //成套件名称
            specificationsModel: data[i].invspecBefore, //成套件规格型号
            unit: data[i].measnameBefore, //成套件单位
            sumQuantity: data[i].inQuantity, //成套件数量

            stornameAfter: data[i].stornameAfter, //配件仓库名称
            partsInventoryName: data[i].invnameAfter, //配件名称
            partsSpecificationsModel: data[i].invspecAfter, //配件规格型号
            partsUnit: data[i].measnameAfter, //配件单位
            partsSumQuantity: data[i].outQuantity, //配件数量
          };
          dataSource.push(Data);
        }
        this.dataSource = dataSource;
        if (this.dataSource == undefined || this.dataSource.length <= 0) {
          this.$message.warning("暂无符合查询条件的数据");
        }
      });
    },
    //更改时间格式
    getdateOfSignature() {
      if (this.formdata.dateOfSignature[0]) {
        return `${moment(this.formdata.dateOfSignature[0]).format(
          "YYYY-MM-DD"
        )}`;
      } else {
        return "";
      }
    },
    //更改时间格式
    getdateOfSignature1() {
      if (this.formdata.dateOfSignature[1]) {
        return `${moment(this.formdata.dateOfSignature[1]).format(
          "YYYY-MM-DD"
        )}`;
      } else {
        return "";
      }
    },
    //更改时间格式
    getAccountingDate() {
      if (this.formdata.AccountingDate[0]) {
        return `${moment(this.formdata.AccountingDate[0]).format("YYYY-MM")}`;
      } else {
        return "";
      }
    },
    //更改时间格式
    getAccountingDate1() {
      if (this.formdata.AccountingDate[1]) {
        return `${moment(this.formdata.AccountingDate[1]).format("YYYY-MM")}`;
      } else {
        return "";
      }
    },
    //查询按钮
    onSubmit() {
      let formdata = this.formdata;
      console.log(formdata, "formdata");
      let queryStr = "";

      // 仓库名称
      if (formdata.pkStordoc.length > 0) {
        queryStr += "&pkStordoc=";
        let pkStordoc = [];
        formdata.pkStordoc.forEach((item) => {
          const pkStordocItem = item.split("|")[2];
          pkStordoc.push(pkStordocItem);
        });
        queryStr += pkStordoc.join(",");
      }

      // 客户
      if (formdata.clientId) {
        queryStr += `&clientId=${formdata.clientId}`;
      }

      // 成套件名称
      if (formdata.invcodeAftere) {
        queryStr += `&pkInvbasdocBefore=${formdata.invcodeAftere}`;
      }

      // 会计日期（精确到月份）
      if (formdata.AccountingDate.length > 0) {
        queryStr += `&accountingPeriodBegin=${moment(
          formdata.AccountingDate[0]
        ).format("YYYY-MM")}`;
        queryStr += `&accountingPeriodEnd=${moment(
          formdata.AccountingDate[1]
        ).format("YYYY-MM")}`;
      }
      // 业务日期 （精确到天)
      if (formdata.dateOfSignature.length > 0) {
        queryStr += `&beginDate=${moment(formdata.dateOfSignature[0]).format(
          "YYYY-MM-DD"
        )}`;
        queryStr += `&endDate=${moment(formdata.dateOfSignature[1]).format(
          "YYYY-MM-DD"
        )}`;
      }

      this.queryStr = queryStr;
      console.log(queryStr, "queryStr");
      this.getlist();
    },
    // 重置按钮
    reset() {
      this.formdata = {
        pkStordoc: [], //所属单位
        packageInventory: [], //成套件名称
        invcodeAfter: "",
        // stockCode: "", //存货编码
        // stockCode1: "",
        // stockCode2: "",
        // stockName: "",
        farmer: "", //农户
        dateOfSignature: [], //业务日期
        AccountingDate: [], //会计日期
      };
      this.queryStr = "";
      this.pagination.current = 1;
      this.getlist();
    },
    invcodeAftereChange(value, option) {
      console.log(value, option);
      this.formdata.id = option.key;

      this.formdata.invcodeAftere = value.split("|")[3]; // 存货名称主键
    },
    //弹出日历和关闭日历的回调
    onChange(date, dateString) {
      console.log(date, dateString);
    },
    // 分页函数
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.queryParam.page = pagination.current;
      this.queryParam.size = pagination.pageSize;
      this.getlist();
    },
    // 导出
    exportToExcel() {
      this.showSpin = true; //打印加载
      $http
        .zuzhuangselect(
          "?pageNo=1&auditMark=1&pageSize=" + this.maxSize + this.queryStr
        )
        .then((res) => {
          console.log("导出的数据", res.result.list);
          let array = res.result.list;
          this.exportBasic(array);
        });
    },
    //  接收数组，进行导出
    exportBasic(Array) {
      console.log("要导出的数据为:::::", Array);
      //  规整要导出的数据:::::
      let array = [];
      for (let i = 0; i < Array.length; i++) {
        let data = {
          序号: i + 1,
          成套件仓库名称: Array[i].stornameBefore,
          成套件名称: Array[i].invnameBefore,
          成套件规格型号: Array[i].invspecBefore,
          成套件单位: Array[i].measnameBefore,
          成套件数量: Array[i].inQuantity,
          配件仓库名称: Array[i].stornameAfter,
          配件名称: Array[i].invnameAfter,
          配件规格型号: Array[i].invspecAfter,
          配件单位: Array[i].measnameAfter,
          配件数量: Array[i].outQuantity,
        };
        array.push(data);
      }
      // 生成 sheet 表格 数据
      let sheet = XLSX.utils.json_to_sheet(array, {
        // 对导出内容进行相应的排序,手动排序。
        header: [
          "序号",
          "成套件仓库名称",
          "成套件名称",
          "成套件规格型号",
          "成套件单位",
          "成套件数量",
          "配件仓库名称",
          "配件名称",
          "配件规格型号",
          "配件单位",
          "配件数量",
        ],
      });
      // 生成导出表格
      let blob = sheet2blob(sheet);
      try {
        FileSaver.saveAs(
          new Blob([blob], {
            type: "application/octet-stream",
          }),
          "组转汇总表.xlsx" // 导出文件夹名称
        );
      } catch (e) {
        console.log(e);
      }
      this.showSpin = false; //导出中
    },
  },
  mounted() {
    this.getApplyStorage(); // 获取仓库编码、名称
    this.getPartsInventoryInformationList(); // 获取成套件
    this.getlist(); //获取主列表
  },
};
</script>
